package com.banksoft.cps.controller;

import com.banksoft.cps.bean.FileInfo;
import com.banksoft.cps.service.FileInfoService;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Controller
@RequestMapping({"/file"})
public class FileController extends ControllerConstants
{

    @Autowired
    FileInfoService fileInfoService;

    @RequestMapping(value={"/uploadFile"}, produces={"application/json;charset=UTF-8"})
    public String uploadFileAction(HttpServletRequest request, HttpServletResponse response, HttpSession session)
    {
        response.setContentType("text/html;charset=utf-8");
        System.out.println("开始");
        List FileList = new ArrayList();
        try
        {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
            Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
            String path = getPath(request);

            System.out.println(path);
            File targetFile = new File(path);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            for (Entry entry : fileMap.entrySet()) {
                MultipartFile mf = (MultipartFile)entry.getValue();
                String originalFilename = mf.getOriginalFilename();
                long size = mf.getSize();
                if ((StringUtils.isNotBlank(originalFilename)) && (size > 0L)) {
                    String fileName = getDatePartOfFileName() + originalFilename;
                    String saveFileName = fileName;

                    fileName = getWebFileName(fileName);
                    File uploadFile = new File(path + File.separator + fileName);
                    FileCopyUtils.copy(mf.getBytes(), uploadFile);
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setUserId("");
                    fileInfo.setName(originalFilename);
                    fileInfo.setPath("/uploadFiles/" + fileName);
                    fileInfoService.saveFile(fileInfo);
                    FileList.add(fileInfo);
                }
            }

            response.getWriter().write(toJSONString(createDataTip(FileList)));
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping(value={"/delete"}, produces={"application/json;charset=UTF-8"})
    @ResponseBody
    public String deleteFile(String fileId, HttpServletRequest request, HttpServletResponse response, HttpSession session)
    {
        FileInfo fileInfo = this.fileInfoService.queryFile(fileId);
        String fileInfoPath = fileInfo.getPath();
        String fileName = fileInfoPath.substring(fileInfoPath.lastIndexOf("/"));
        File file = new File(getPath(request) + File.separator + fileName);
        file.delete();
        this.fileInfoService.deleteFile(fileId);
        return toJSONString(SUCCESS);
    }

    private String getPath(HttpServletRequest request)
    {
        String path = request.getSession().getServletContext().getRealPath("/") + "uploadFiles";
        return path;
    }

    public static String getWebFileName(String fileName)
    {
        String result = null;
        int index = fileName.lastIndexOf(".");
        if (index > 0) {
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            String fileOriginName = fileName.substring(0, fileName.lastIndexOf("."));
            result = DigestUtils.md5Hex(fileOriginName) + fileType;
        } else {
            result = DigestUtils.md5Hex(fileName);
        }

        return result;
    }
    public String getDatePartOfFileName()
    {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(now);
    }
}
